<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="设备编码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入设备编码"/>
      </el-form-item>
      <el-form-item label="所属人" prop="ownerId">
        <el-select v-model="formData.ownerId" clearable placeholder="请选择所属人">
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单元" prop="unitId">
        <el-tree-select
          v-model="formData.unitId"
          :data="unitTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择部门"
          value-key="deptId"
        />
      </el-form-item>
      <el-form-item label="标签" prop="tag">
        <el-input v-model="formData.tag" placeholder="请输入标签"/>
      </el-form-item>
      <el-form-item label="部门" prop="departmentId">
        <el-tree-select
          v-model="formData.departmentId"
          :data="deptTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择部门"
          value-key="deptId"
        />
      </el-form-item>
      <el-form-item label="采购时间" prop="procurementTime">
        <el-date-picker
          v-model="formData.procurementTime"
          type="date"
          value-format="x"
          placeholder="选择采购时间"
        />
      </el-form-item>
      <el-form-item label="投入时间" prop="usageTime">
        <el-date-picker
          v-model="formData.usageTime"
          type="date"
          value-format="x"
          placeholder="选择投入时间"
        />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {DeviceInstanceApi, DeviceInstanceVO} from '@/api/zjyj/deviceinstance';
import * as UserApi from '@/api/system/user';
import {defaultProps, handleTree} from '@/utils/tree';
import * as DeptApi from '@/api/system/dept';
import {TenantUnitApi} from '@/api/zjyj/tenantunit';
import {useRoute} from 'vue-router'

const route = useRoute()
/** 设备实例 表单 */
defineOptions({name: 'DeviceInstanceForm'});

const {t} = useI18n(); // 国际化
const message = useMessage(); // 消息弹窗

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(''); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(''); // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deviceId: undefined,
  code: undefined,
  procurementTime: undefined,
  ownerId: undefined,
  tag: undefined,
  usageTime: undefined,
  unitId: undefined,
  departmentId: undefined
});
const formRules = reactive({
  deviceId: [{required: true, message: '设备id不能为空', trigger: 'blur'}],
  code: [{required: true, message: '设备编码不能为空', trigger: 'blur'}],
  procurementTime: [{required: false, message: '采购时间不能为空', trigger: 'blur'}],
  ownerId: [{required: true, message: '所属人不能为空', trigger: 'blur'}],
  tag: [{required: true, message: '标签不能为空', trigger: 'blur'}],
  usageTime: [{required: false, message: '投入时间不能为空', trigger: 'blur'}],
  unitId: [{required: true, message: '单元不能为空', trigger: 'blur'}],
  departmentId: [{required: true, message: '部门不能为空', trigger: 'blur'}]
});
const formRef = ref(); // 表单 Ref
const userList = ref<UserApi.UserVO[]>([]); // 用户列表
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true;
  dialogTitle.value = t('action.' + type);
  formType.value = type;
  resetForm();
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await DeviceInstanceApi.getDeviceInstance(id);
    } finally {
      formLoading.value = false;
    }
  }
  userList.value = await UserApi.getSimpleUserList();
  await initDeptUnit();
};
defineExpose({open}); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    formData.value.deviceId = Number(route.query.deviceId);
    const data = formData.value as unknown as DeviceInstanceVO;
    if (formType.value === 'create') {
      await DeviceInstanceApi.createDeviceInstance(data);
      message.success(t('common.createSuccess'));
    } else {
      await DeviceInstanceApi.updateDeviceInstance(data);
      message.success(t('common.updateSuccess'));
    }
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

const deptTree = ref() // 树形结构
const unitTree = ref() // 树形结构

const initDeptUnit = async () => {
  deptTree.value = handleTree(await DeptApi.getSimpleDeptList())
  unitTree.value = handleTree(await TenantUnitApi.getSimpleUnitList())
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceId: undefined,
    code: undefined,
    procurementTime: undefined,
    ownerId: undefined,
    tag: undefined,
    usageTime: undefined,
    unitId: undefined,
    departmentId: undefined
  };
  formRef.value?.resetFields();
};
</script>
